<template>
  <div class="invoice-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>发票管理</h2>
        <p class="page-description">管理企业发票信息，包括开票、收票、发票状态跟踪等</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增发票
        </el-button>
        <el-button type="success" @click="handleBatchIssue">
          <el-icon><Document /></el-icon>
          批量开票
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="发票号码">
          <el-input
            v-model="searchForm.invoiceNumber"
            placeholder="请输入发票号码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="发票类型">
          <el-select
            v-model="searchForm.invoiceType"
            placeholder="请选择发票类型"
            clearable
            style="width: 150px"
          >
            <el-option label="增值税专用发票" value="vat_special" />
            <el-option label="增值税普通发票" value="vat_ordinary" />
            <el-option label="电子发票" value="electronic" />
            <el-option label="收据" value="receipt" />
          </el-select>
        </el-form-item>
        <el-form-item label="发票状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="草稿" value="draft" />
            <el-option label="已开票" value="issued" />
            <el-option label="已发送" value="sent" />
            <el-option label="已收票" value="received" />
            <el-option label="已作废" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon issued">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.issuedCount }}</div>
                <div class="stat-label">已开票数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon received">
                <el-icon><Folder /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.receivedCount }}</div>
                <div class="stat-label">已收票数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon amount">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ stats.totalAmount }}</div>
                <div class="stat-label">发票总金额</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon tax">
                <el-icon><Coin /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ stats.totalTax }}</div>
                <div class="stat-label">税额合计</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="filteredTableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNumber" label="发票号码" width="150" />
        <el-table-column prop="invoiceType" label="发票类型" width="130">
          <template #default="{ row }">
            <el-tag :type="getInvoiceTypeTag(row.invoiceType)">{{ getInvoiceTypeName(row.invoiceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="150" />
        <el-table-column prop="issueDate" label="开票日期" width="120" />
        <el-table-column prop="amount" label="不含税金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ formatNumber(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="taxAmount" label="税额" width="100" align="right">
          <template #default="{ row }">
            <span class="tax-amount">¥{{ formatNumber(row.taxAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="价税合计" width="120" align="right">
          <template #default="{ row }">
            <span class="total-amount">¥{{ formatNumber(row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleView(row)">
              详情
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handlePrint(row)"
              v-if="row.status === 'issued'"
            >
              打印
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
              v-if="['draft', 'issued'].includes(row.status)"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="formData.invoiceType" placeholder="请选择发票类型" style="width: 100%">
                <el-option label="增值税专用发票" value="vat_special" />
                <el-option label="增值税普通发票" value="vat_ordinary" />
                <el-option label="电子发票" value="electronic" />
                <el-option label="收据" value="receipt" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户税号" prop="customerTaxNumber">
              <el-input v-model="formData.customerTaxNumber" placeholder="请输入客户税号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="issueDate">
              <el-date-picker
                v-model="formData.issueDate"
                type="date"
                placeholder="请选择开票日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="不含税金额" prop="amount">
              <el-input-number
                v-model="formData.amount"
                :precision="2"
                :min="0"
                style="width: 100%"
                @change="calculateTax"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-select v-model="formData.taxRate" @change="calculateTax" style="width: 100%">
                <el-option label="0%" :value="0" />
                <el-option label="3%" :value="3" />
                <el-option label="6%" :value="6" />
                <el-option label="9%" :value="9" />
                <el-option label="13%" :value="13" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税额">
              <el-input-number
                v-model="formData.taxAmount"
                :precision="2"
                :min="0"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价税合计">
              <el-input-number
                v-model="formData.totalAmount"
                :precision="2"
                :min="0"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio label="draft">草稿</el-radio>
                <el-radio label="issued">已开票</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh, Document, Folder, Money, Coin } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  invoiceNumber: '',
  invoiceType: '',
  status: '',
  dateRange: []
})

// 表单数据
const formData = reactive({
  id: null,
  invoiceType: '',
  customerName: '',
  customerTaxNumber: '',
  issueDate: '',
  amount: 0,
  taxRate: 13,
  taxAmount: 0,
  totalAmount: 0,
  status: 'draft',
  remark: ''
})

// 表单验证规则
const formRules = {
  invoiceType: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  customerTaxNumber: [
    { required: true, message: '请输入客户税号', trigger: 'blur' }
  ],
  issueDate: [
    { required: true, message: '请选择开票日期', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入不含税金额', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 统计数据
const stats = reactive({
  issuedCount: 45,
  receivedCount: 38,
  totalAmount: '1,256,789.50',
  totalTax: '163,382.64'
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    invoiceNumber: '12345678901234567890',
    invoiceType: 'vat_special',
    customerName: '北京科技有限公司',
    customerTaxNumber: '91110000123456789X',
    issueDate: '2024-03-01',
    amount: 100000.00,
    taxRate: 13,
    taxAmount: 13000.00,
    totalAmount: 113000.00,
    status: 'issued',
    remark: '软件开发服务费'
  },
  {
    id: 2,
    invoiceNumber: '12345678901234567891',
    invoiceType: 'vat_ordinary',
    customerName: '上海贸易有限公司',
    customerTaxNumber: '91310000123456789Y',
    issueDate: '2024-03-02',
    amount: 50000.00,
    taxRate: 6,
    taxAmount: 3000.00,
    totalAmount: 53000.00,
    status: 'sent',
    remark: '咨询服务费'
  },
  {
    id: 3,
    invoiceNumber: '12345678901234567892',
    invoiceType: 'electronic',
    customerName: '广州制造有限公司',
    customerTaxNumber: '91440000123456789Z',
    issueDate: '2024-03-03',
    amount: 75000.00,
    taxRate: 13,
    taxAmount: 9750.00,
    totalAmount: 84750.00,
    status: 'received',
    remark: '设备销售'
  },
  {
    id: 4,
    invoiceNumber: '',
    invoiceType: 'vat_special',
    customerName: '深圳电子有限公司',
    customerTaxNumber: '91440300123456789A',
    issueDate: '2024-03-04',
    amount: 120000.00,
    taxRate: 13,
    taxAmount: 15600.00,
    totalAmount: 135600.00,
    status: 'draft',
    remark: '技术服务费'
  },
  {
    id: 5,
    invoiceNumber: '12345678901234567893',
    invoiceType: 'vat_ordinary',
    customerName: '杭州网络有限公司',
    customerTaxNumber: '91330000123456789B',
    issueDate: '2024-03-05',
    amount: 80000.00,
    taxRate: 6,
    taxAmount: 4800.00,
    totalAmount: 84800.00,
    status: 'issued',
    remark: '网络服务费'
  },
  {
    id: 6,
    invoiceNumber: '12345678901234567894',
    invoiceType: 'electronic',
    customerName: '成都软件有限公司',
    customerTaxNumber: '91510000123456789C',
    issueDate: '2024-03-06',
    amount: 60000.00,
    taxRate: 13,
    taxAmount: 7800.00,
    totalAmount: 67800.00,
    status: 'cancelled',
    remark: '软件授权费'
  }
])

// 计算属性 - 过滤后的表格数据
const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (searchForm.invoiceNumber) {
    data = data.filter(item => 
      item.invoiceNumber.includes(searchForm.invoiceNumber)
    )
  }
  
  if (searchForm.invoiceType) {
    data = data.filter(item => item.invoiceType === searchForm.invoiceType)
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    data = data.filter(item => {
      const itemDate = new Date(item.issueDate)
      return itemDate >= startDate && itemDate <= endDate
    })
  }
  
  pagination.total = data.length
  
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return data.slice(start, end)
})

// 方法
const handleSearch = () => {
  pagination.currentPage = 1
}

const handleReset = () => {
  Object.assign(searchForm, {
    invoiceNumber: '',
    invoiceType: '',
    status: '',
    dateRange: []
  })
  pagination.currentPage = 1
}

const handleAdd = () => {
  dialogTitle.value = '新增发票'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑发票'
  isEdit.value = true
  Object.assign(formData, {
    ...row,
    issueDate: row.issueDate ? new Date(row.issueDate) : ''
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info(`查看发票详情: ${row.invoiceNumber || '草稿'}`)
}

const handlePrint = (row) => {
  ElMessage.success(`打印发票: ${row.invoiceNumber}`)
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要作废发票 "${row.invoiceNumber || '草稿'}" 吗？`,
      '作废确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = 'cancelled'
      ElMessage.success('作废成功')
    }
  } catch {
    ElMessage.info('已取消作废')
  }
}

const handleBatchIssue = () => {
  ElMessage.success('批量开票功能开发中...')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index > -1) {
        Object.assign(tableData.value[index], {
          ...formData,
          issueDate: formData.issueDate ? formData.issueDate.toISOString().split('T')[0] : '',
          invoiceNumber: formData.status === 'issued' && !tableData.value[index].invoiceNumber 
            ? generateInvoiceNumber() 
            : tableData.value[index].invoiceNumber
        })
        ElMessage.success('更新成功')
      }
    } else {
      const newInvoice = {
        ...formData,
        id: Date.now(),
        issueDate: formData.issueDate ? formData.issueDate.toISOString().split('T')[0] : '',
        invoiceNumber: formData.status === 'issued' ? generateInvoiceNumber() : ''
      }
      tableData.value.unshift(newInvoice)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
  } catch {
    ElMessage.error('表单验证失败')
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    invoiceType: '',
    customerName: '',
    customerTaxNumber: '',
    issueDate: '',
    amount: 0,
    taxRate: 13,
    taxAmount: 0,
    totalAmount: 0,
    status: 'draft',
    remark: ''
  })
}

const calculateTax = () => {
  if (formData.amount && formData.taxRate) {
    formData.taxAmount = (formData.amount * formData.taxRate / 100)
    formData.totalAmount = formData.amount + formData.taxAmount
  }
}

const generateInvoiceNumber = () => {
  const timestamp = Date.now().toString()
  return timestamp.padStart(20, '1')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  console.log('选中的行:', selection)
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
}

// 工具方法
const getInvoiceTypeName = (type) => {
  const typeMap = {
    vat_special: '专用发票',
    vat_ordinary: '普通发票',
    electronic: '电子发票',
    receipt: '收据'
  }
  return typeMap[type] || type
}

const getInvoiceTypeTag = (type) => {
  const tagMap = {
    vat_special: 'danger',
    vat_ordinary: 'primary',
    electronic: 'success',
    receipt: 'info'
  }
  return tagMap[type] || ''
}

const getStatusName = (status) => {
  const statusMap = {
    draft: '草稿',
    issued: '已开票',
    sent: '已发送',
    received: '已收票',
    cancelled: '已作废'
  }
  return statusMap[status] || status
}

const getStatusTag = (status) => {
  const tagMap = {
    draft: 'info',
    issued: 'success',
    sent: 'primary',
    received: 'warning',
    cancelled: 'danger'
  }
  return tagMap[status] || ''
}

const formatNumber = (num) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(num)
}

// 生命周期
onMounted(() => {
  // 初始化数据
  pagination.total = tableData.value.length
})
</script>

<style scoped>
.invoice-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.issued {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.received {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.amount {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.tax {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.table-card {
  margin-bottom: 20px;
}

.amount-text {
  font-weight: 600;
  color: #409eff;
}

.tax-amount {
  font-weight: 600;
  color: #e6a23c;
}

.total-amount {
  font-weight: 600;
  color: #67c23a;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
}
</style>